package com.onepice.mlp.core.serviceImpl;

import com.onepice.mlp.core.service.TagdataService;
import com.onepice.mlp.data.dao.TagdataDao;
import com.onepice.mlp.data.entity.Tagdata;
import com.onepice.mlp.utils.commom.ConvUtil;
import com.onepice.mlp.utils.commom.PageUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author FireWang
 * @date 2024/11/11 22:50:13
 */
@Service
@AllArgsConstructor
@Transactional
public class TagdataServiceImpl implements TagdataService {
    private TagdataDao tagdataDao;

    @Override
    public List<Tagdata> getAll() {
        return tagdataDao.findAll();
    }

    @Override
    public Tagdata getById(Integer id) {
        Optional<Tagdata> tagdata = tagdataDao.findById(id);
        return tagdata.get();
    }

    @Override
    public void insert(Tagdata tagdata) {
        tagdata.setCreateTime(new Date());
        tagdataDao.save(tagdata);
    }

    @Override
    public void update(Tagdata tagdata) {
        tagdata.setModifyTime(new Date());
        tagdataDao.save(tagdata);
    }

    @Override
    public void deleteById(Integer id) {
        tagdataDao.deleteById(id);
    }

    @Override
    public Page<Tagdata> getTagdataForPage(PageUtil page) {
        //查询规格定义
        Specification<Tagdata> specification = new Specification<Tagdata>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<Tagdata> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                String name = ConvUtil.convToString(page.getParamMap().get("name"));
                if (!"".equals(name)) {
                    predicates.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        //分页查询
        return tagdataDao.findAll(specification, page.getPageable());
    }

    @Override
    public Tagdata getByLngLat(String lng, String lat) throws Exception {
        return tagdataDao.findByTestPointLngAndTestPointLat(lng, lat);
    }
}
